/**
 *
 */
package com.elite.groovy.callback


import com.elite.groovy.util.EliteBean
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import net.sf.json.JSONObject
import com.rabbitmq.client.Connection
import com.rabbitmq.client.ConnectionFactory
import com.rabbitmq.client.Channel
import cn.com.elite.PropertiesUtil
/**
 * @use 定时调度，将符合要求数据送到智能回访中心
 * @author chopper
 *
 */

class sendRabbitMqDay implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(sendRabbitMqDay.class)
	String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){
		JSONObject result = new JSONObject();
		log.debug("-----智能回访推送start----------");

		try {
			getNewOrder(eliteBean)
			result.put("code", "1");
			result.put("msg", "");
			return result;
		}catch(Exception e) {
			log.error("ErrorMessage:",e);
			result.put("code", "-1");
			result.put("msg", "fail");
			return result;
		}
	}
/**
 * @use 推送增值回访消息
 * @return
 * @throws Exception
 */
	private static boolean getNewOrder(EliteBean eliteBean) throws Exception{
		//定义MQ推送结果
		boolean sendMsgStatus = false;

		/**
		 * @use 结案回访数据查询和推送信息拼接
		 *
		 */
		log.debug("-----推送增值回访消息：结案 JA 回访推送start----------");
		String querysql3=''' SELECT
										to_char( v.createddate, 'yyyy-mm-dd hh24:mi:ss' ) v_nowdate,
										v.visittask_guid visittask_guid,
										q.registno registno,
										q.licenseno licenseno,
										q.policyno policyno,
										q.prplregistregistno prplregistregistno,
										q.prplregistreportorname prplregistreportorname,
										q.prplregistreportorphonenumber prplregistreportorphonenumber,
										to_char( q.enddate, 'yyyy-mm-dd hh:mi:ss' ) enddate,
										rp.ROLEGROUPDESCRIPTION handlercode,
										to_char( q.prplcompensatesumdutypaid ) prplcompensatesumdutypaid,
										to_char( q.createtime, 'yyyy-mm-dd hh:mi:ss' ) createtime,
										q.status status,
										to_char( q.paidtime, 'yyyy-mm-dd hh:mi:ss' ) paidtime,
										q.insuredname insuredname,
										q.identifynumberid identifynumberid,
										q.riskcode riskcode,
										q.prplregistregistriskcode prplregistregistriskcode,
										q.IS_SOUTHNET_EMP issouthnetemp,
										q.IS_DHIC_EMP isdhicemp,
										q.PAYEENAME payeename,
										q.PAYEEMOBILE payeemobile,
										p.parameter_desc parameter_desc,
										substr( r.happened_time, 1, 10 ) happened_time,
										r.examine_address examine_address,
										r.accident_course accident_course,
										r.brand_name brand_name
									FROM
										Ob_visitTask v
										LEFT JOIN DH_REPORT r ON r.clm_no = v.businessno
										LEFT JOIN ETL_PRPCMAIN e ON e.POLICYNO = r.policy_no
										LEFT JOIN CUSTOM_PARAMETER p ON p.parameter_id = e.businessclass
										AND p.parameter_type = 'businessclass'
										LEFT JOIN (
													SELECT
														ROW_NUMBER ( ) OVER ( PARTITION BY p.registno ORDER BY p.enddate ) prn,
														p.*
													FROM
														cc_core_case_closed p
													WHERE
														p.prplcompensatesumdutypaid > 0
														AND p.enddate < SYSDATE - 4
														AND p.status = '1'
														AND p.prplregistreportorphonenumber IS NOT NULL
										) q ON q.registno = v.businessno
										AND q.prn = 1
										LEFT JOIN rolegroup rp ON rp.ORG_ID = (CASE
												WHEN substr( q.policyno, 2, 2 ) = '00' THEN
												substr( q.policyno, 2, 2 ) || '020000'
												WHEN substr( q.policyno, 2, 2 ) != '00' THEN
												substr( q.policyno, 2, 2 ) || '000000' END)
										WHERE
										v.TASKSTATUS = 0
										AND BUSTYPE = 'JA' '''
		List list3=eliteBean.chaxun_sql(querysql3,"dataSource");
		log.debug("推送增值回访消息数据："+list3);

		for(int n=0;n<list3.size();n++){
			def map3=list3[n];
			String v_visittask_guid=map3.get("visittask_guid");//数据唯一guid
			log.debug("本次推送增值回访visittask_guid："+v_visittask_guid);

			JSONObject json = new JSONObject();
			json.put("ID", map3.get("visittask_guid")  ==null?"":(String)map3.get("visittask_guid"));
			json.put("PolicyNo", map3.get("policyno")  ==null?"":(String)map3.get("policyno"));
			json.put("ClmNo", map3.get("registno")  ==null?"":(String)map3.get("registno"));
			json.put("LicenseNo", map3.get("licenseno")  ==null?"":(String)map3.get("licenseno"));
			json.put("InsuredName", map3.get("insuredname")  ==null?"":(String)map3.get("insuredname"));
			json.put("DepartName", map3.get("handlercode")  ==null?"":(String)map3.get("handlercode"));
			json.put("BusinessClass", map3.get("parameter_desc")  ==null?"":(String)map3.get("parameter_desc"));
			json.put("PayNumber", map3.get("prplcompensatesumdutypaid")  ==null?"":(String)map3.get("prplcompensatesumdutypaid"));
			json.put("LinkerName", map3.get("prplregistreportorname")  ==null?"":(String)map3.get("prplregistreportorname"));
			json.put("LinkerPhone", map3.get("prplregistreportorphonenumber")  ==null?"":(String)map3.get("prplregistreportorphonenumber"));
			json.put("DamageTime", map3.get("happened_time")  ==null?"":(String)map3.get("happened_time"));
			json.put("EndDate", map3.get("enddate")  ==null?"":(String)map3.get("enddate"));
			json.put("ExamineAddress", map3.get("examine_address")  ==null?"":(String)map3.get("examine_address"));
			json.put("AccidentCourse", map3.get("accident_course")  ==null?"":(String)map3.get("accident_course"));
			json.put("BrandName", map3.get("brand_name")  ==null?"":(String)map3.get("brand_name"));
			json.put("PayeeName", map3.get("payeename")  ==null?"":(String)map3.get("payeename"));
			json.put("PayeePhone", map3.get("payeemobile")  ==null?"":(String)map3.get("payeemobile"));
			json.put("SignTime", map3.get("v_nowdate")  ==null?"":(String)map3.get("v_nowdate"));

			log.debug("推送增值回访至MQ消息报文："+json);
			log.debug("MQ队列：KF_JA_VISIT");
			sendMsgStatus = sendMsg("KF_JA_VISIT","DH_JA_VISIT",json.toString());

			log.debug("推送增值回访完成，更新接口表：Ob_visitTask");

			def updatesql3="update Ob_visitTask set TASKSTATUS=1,sendtime=sysdate where TASKSTATUS=0 and BUSTYPE='JA' and VISITTASK_GUID='"+v_visittask_guid+"'";
			def updatesqlresult3=eliteBean.update(updatesql3,"dataSource");
			log.debug("更新接口表Ob_visitTask结果:"+updatesqlresult3);

		}

		/**
		 * @use 承保新单回访数据查询和推送信息拼接
		 *
		 */
		log.debug("-----承保 POLICY 回访推送start---------");
		def querysql4="select to_char(v.createddate,'yyyy-mm-dd hh24:mi:ss') v_nowdate,v.visittask_guid visittask_guid,sd.certino certino,sd.policyno policyno,sd.licenseno licenseno,sd.frameno frameno,sd.engineno engineno,sd.brandname brandname,sd.riskcode riskcode, sd.insuredname insuredname,sd.insuredsex insuredsex,substr(sd.identifynumber,-4,4) identifynumber,sd.birthdate birthdate,sd.mobile mobile,sd.appliname appliname,sd.makecom makecom,to_char(sd.inputdate,'yyyy-mm-dd hh24:mi:ss') inputdate,to_char(sd.startdate,'yyyy-mm-dd hh24:mi:ss')  startdate,sd.enddate enddate,sd.bisumamount bisumamount,sd.cisumamount cisumamount,sd.agentname agentname,sd.handlername handlername,sd.operatorname operatorname,sd.carattachnature carattachnature,sd.businessnature businessnature,sd.businessplate businessplate,sd.businessclassification businessclassification,sd.businessclass businessclass,sd.businesssubclass businesssubclass,sd.channelclassification channelclassification,sd.channelsource channelsource, sd.businessflag businessflag, sd.othflag othflag,sd.shareholderflag shareholderflag,to_char(sd.payreftime,'yyyy-mm-dd hh24:mi:ss') payreftime,sd.applisex applisex,sd.applibirthday applibirthday,sd.appliidentifynum appliidentifynum,sd.proposalno proposalno,sd.insuredmobile insuredmobile,sd.carbrand carbrand,sd.cartype cartype, sd.enrolldate enrolldate, sd.seatcountshow seatcountshow,sd.POWERTYPE POWERTYPE,sd.CHGOWNERFLAG CHGOWNERFLAG,sd.IS_SOUTHNET_EMP IS_SOUTHNET_EMP,sd.IS_DHIC_EMP IS_DHIC_EMP,rp.ROLEGROUPDESCRIPTION org_id,sd.thirdment thirdment,sd.dept dept,sd.handlerid handlerid,sd.fourthment fourthment from Ob_visitTask v left join dh_POLICY sd on sd.PolicyNo=v.businessno left join rolegroup rp on rp.ORG_ID=(case when substr(sd.policyno,2,2)='00' then substr(sd.policyno,2,2)||'020000' when substr(sd.policyno,2,2)!='00'	then substr(sd.policyno,2,2)||'000000' end)	  where  v.TASKSTATUS=0 and BUSTYPE='POLICY'";
		def list4=eliteBean.chaxun_sql(querysql4,"dataSource");
		log.debug("list4-------------------------------"+list4);
		for(def m=0;m<list4.size;m++){
			def map4=list4[m];
			def v_visittask_guid=map4.get("visittask_guid");//数据唯一guid
			log.debug("v_visittask_guid---------------"+v_visittask_guid);

			JSONObject json = new JSONObject();
			json.put("ID", map4.get("visittask_guid")  ==null?"":(String)map4.get("visittask_guid"));
			json.put("PolicyNo", map4.get("policyno")  ==null?"":(String)map4.get("policyno"));
			json.put("AppliName", map4.get("appliname")  ==null?"":(String)map4.get("appliname"));
			json.put("InsuredName", map4.get("insuredname")  ==null?"":(String)map4.get("insuredname"));
			json.put("InsuredPhone", map4.get("insuredmobile")  ==null?"":(String)map4.get("insuredmobile"));
			json.put("IdentifyNumber", map4.get("identifynumber")  ==null?"":(String)map4.get("identifynumber"));
			json.put("InputDate", map4.get("inputdate")  ==null?"":(String)map4.get("inputdate"));
			json.put("StartDate", map4.get("startdate")  ==null?"":(String)map4.get("startdate"));
			json.put("BisumAmount", map4.get("bisumamount")  ==null?"":(String)map4.get("bisumamount"));
			json.put("CisumAmount", map4.get("cisumamount")  ==null?"":(String)map4.get("cisumamount"));
			json.put("LicenseNo", map4.get("licenseno")  ==null?"000000":(String)map4.get("licenseno"));
			json.put("BrandName", map4.get("brandname")  ==null?"":(String)map4.get("brandname"));
			json.put("CarBrand", map4.get("carbrand")  ==null?"":(String)map4.get("carbrand"));
			json.put("Department", map4.get("org_id")  ==null?"":(String)map4.get("org_id"));
			json.put("BusinessPlate", map4.get("riskcode")  ==null?"":(String)map4.get("businessplate"));
			json.put("RiskCode", map4.get("licenseno")  ==null?"":(String)map4.get("riskcode"));
			json.put("CarAttachNature", map4.get("carattachnature")  ==null?"":(String)map4.get("carattachnature"));
			json.put("CarType", map4.get("cartype")  ==null?"":(String)map4.get("cartype"));
			json.put("BusinessNature", map4.get("businessnature")  ==null?"":(String)map4.get("businessnature"));
			json.put("BusinessClassification", map4.get("businessclassification")  ==null?"":(String)map4.get("businessclassification"));
			json.put("BusinessSubClass", map4.get("businesssubclass")  ==null?"":(String)map4.get("businesssubclass"));
			json.put("BusinessClass", map4.get("businessclass")  ==null?"":(String)map4.get("businessclass"));
			json.put("ChannelSource", map4.get("channelsource")  ==null?"":(String)map4.get("channelsource"));
			json.put("ChannelClassification", map4.get("channelclassification")  ==null?"":(String)map4.get("channelclassification"));
			json.put("BusinessFlag", map4.get("businessflag")  ==null?"":(String)map4.get("businessflag"));
			json.put("ShareHolderFlag", map4.get("shareholderflag")  ==null?"":(String)map4.get("shareholderflag"));
			json.put("OthFlag", map4.get("othflag")  ==null?"":(String)map4.get("othflag"));
			json.put("Certino", map4.get("certino")  ==null?"":(String)map4.get("certino"));
			json.put("PayrefTime", map4.get("payreftime")  ==null?"":(String)map4.get("payreftime"));
			json.put("AgentName", map4.get("agentname")  ==null?"":(String)map4.get("agentname"));
			json.put("HandlerName", map4.get("handlername")  ==null?"":(String)map4.get("handlername"));
			json.put("OperatorName", map4.get("operatorname")  ==null?"":(String)map4.get("operatorname"));
			json.put("Thirdment", map4.get("thirdment")  ==null?"":(String)map4.get("thirdment"));
			json.put("Dept", map4.get("dept")  ==null?"":(String)map4.get("dept"));
			json.put("HandlerId", map4.get("handlerid")  ==null?"":(String)map4.get("handlerid"));
			json.put("Fourthment", map4.get("fourthment")  ==null?"":(String)map4.get("fourthment"));
			json.put("SignTime", map4.get("v_nowdate")  ==null?"":(String)map4.get("v_nowdate"));

			log.debug("承保推送报文------------------------"+json);
			sendMsgStatus = sendMsg("EX_VHE_CS_POLICY","VHE_CS_POLICY",json.toString());
			/**
			 * @use 承保新单回访已推送更新结果
			 *
			 */
			log.debug("-----承保 POLICY 回访推送完成更新接口表---------");
			def updatesql4="update Ob_visitTask set TASKSTATUS=1,sendtime=sysdate where TASKSTATUS=0 and BUSTYPE='POLICY' and VISITTASK_GUID='"+v_visittask_guid+"'";
			def updatesqlresult4=eliteBean.update(updatesql4,"dataSource");
			log.debug("updatesqlresult4:"+updatesqlresult4);

		}

		/**
		 * @use 互联网新单回访数据查询和推送信息拼接
		 *
		 */
		log.debug("-----互联网新单 NET 回访推送start---------");
		//230525 taskstatus=4 的 多次投保 也推送机器人，被保人姓名拼接到一起
		def querysql5="select to_char(ov.createddate,'yyyy-mm-dd hh24:mi:ss') v_nowdate, ov.taskstatus, ov.visittask_guid,ov.businessno,ev.goodsname,ev.productcode,ev.productname,ev.appliname,ev.insurantname,ev.applimobile,ev.insuredmobile,ev.startdate,ev.enddate,ev.comcode,ev.businessclass,ev.businessplate from ob_visittask ov left join elite_net_visit_data ev on ov.businessno = ev.policyno where ov.bustype='NET' and (ov.taskstatus=0 or ov.taskstatus=4) and to_char(ov.createddate,'yyyy-mm-dd')=to_char(sysdate,'yyyy-mm-dd')";


		def list5=eliteBean.chaxun_sql(querysql5,"dataSource");
		log.debug("互联网推送数:"+list5.size());
		for(def m=0;m<list5.size();m++){
			def map5=list5[m];
			def v_visittask_guid=map5.get("visittask_guid");//数据唯一guid
			log.debug("v_visittask_guid---------------"+v_visittask_guid);

			JSONObject json = new JSONObject();
			json.put("ID", map5.get("visittask_guid")  ==null?"":(String)map5.get("visittask_guid"));
			json.put("PolicyNo", map5.get("businessno")  ==null?"":(String)map5.get("businessno"));
			json.put("GoodsName", map5.get("goodsname")  ==null?"":(String)map5.get("goodsname"));
			json.put("ProductCode", map5.get("productcode")  ==null?"":(String)map5.get("productcode"));
			json.put("ProductName", map5.get("productname")  ==null?"":(String)map5.get("productname"));
			json.put("AppliName", map5.get("appliname")  ==null?"":(String)map5.get("appliname"));
			if(map5.get("taskstatus")!=null&&"4".equals((String)map5.get("taskstatus"))&&(String)map5.get("productcode")!=null&&map5.get("applimobile")!=null){
				//查询多次投保的关联保单，取被保人姓名拼接到一起，按逗号隔开
				def insQrysql="select insurantname from elite_net_visit_data where applimobile='" +(String)map5.get("applimobile")+ "' and productcode='" +(String)map5.get("productcode")+ "' and to_char(updatetime,'YYYY-MM-DD')=to_char(SYSDATE,'YYYY-MM-DD')";
				log.debug("insQrysql---------------"+insQrysql);
				def insList=eliteBean.chaxun_sql(insQrysql,"dataSource");
				log.debug("insList---------------"+insList.toString());

				StringBuffer insstr = new StringBuffer();
				insstr.append("");
				for(int t=0;t<insList.size();t++){
					String insurantname=insList[t].get("insurantname");
					if(insurantname!=null){
						if(t==insList.size()-1||t==2){
							insstr.append(insurantname);
							if(insList.size()>3){
								insstr.append("等");
							}
							break;
						}else{
							insstr.append(insurantname).append(",");
						}
					}
				}
				json.put("InsurantName",insstr.toString());
			}else{
				json.put("InsurantName", map5.get("insurantname")  ==null?"":(String)map5.get("insurantname"));
			}

			json.put("AppliMobile", map5.get("applimobile")  ==null?"":(String)map5.get("applimobile"));
			json.put("InsuredMobile", map5.get("insuredmobile")  ==null?"":(String)map5.get("insuredmobile"));
			json.put("StartDate", map5.get("startdate")  ==null?"":(String)map5.get("startdate"));
			json.put("EndDate", map5.get("enddate")  ==null?"000000":(String)map5.get("enddate"));
			json.put("ComName", map5.get("comcode")  ==null?"":(String)map5.get("comcode"));
			json.put("BusinessClass", map5.get("businessclass")  ==null?"":(String)map5.get("businessclass"));
			json.put("BusinessNature", map5.get("businessplate")  ==null?"":(String)map5.get("businessplate"));
			json.put("SignTime", map5.get("v_nowdate")  ==null?"":(String)map5.get("v_nowdate"));
			log.debug("互联网推送报文------------------------"+json);
			sendMsg("EX_NET_POLICY_VISIT","NET_POLICY_VISIT",json.toString());
			/**
			 * @use 互联网回访已推送更新结果
			 *
			 */
			log.debug("-----互联网 NET 回访推送完成更新接口表---------");
			def updatesql5="update Ob_visitTask set TASKSTATUS=1,sendtime=sysdate where (TASKSTATUS=0 or TASKSTATUS=4) and BUSTYPE='NET' and VISITTASK_GUID='"+v_visittask_guid+"'";
			def updatesqlresult5=eliteBean.update(updatesql5,"dataSource");
			log.debug("updatesqlresult5:"+updatesqlresult5);

		}

	}
	/**
	 * @use RabbitMq发送队列消息
	 * @param exchangename
	 * @param routingkey
	 * @param msg
	 * @return
	 * @throws Exception
	 */
	private static boolean sendMsg(String exchangename,String routingkey,String msg) throws Exception{

		log.debug("===================发送RabbitMq消息=====================");
		// 获取到连接以及mq通道
		Connection connection = getConnection();
		// 从连接中创建通道
		Channel channel = connection.createChannel();
		// 声明exchange
		channel.exchangeDeclare(exchangename, "topic",true);
		channel.queueDeclare(routingkey, false, false, false, null);
		// 绑定队列到交换机，并设置路由键
		channel.queueBind(routingkey,exchangename,routingkey);
		def ret = channel.basicPublish(exchangename, routingkey, null, msg.getBytes("UTF-8"));
		log.debug("MQ发送结果"+routingkey+":"+ret);
		//关闭通道和连接
		channel.close();
		connection.close();
		return true
	}


	/**
	 * @use RabbitMq创建连接
	 * @return
	 * @throws Exception
	 */
	private static Connection getConnection() throws Exception {
		String string = new String("中".getBytes("UTF-8"),"GBK");
		PropertiesUtil p = new PropertiesUtil();
		String host =p.readValue("MQhost");
		int port = 5672;
		String vhost = p.readValue("MQvirtualhost");
		String username = p.readValue("MQuserName");
		String password = p.readValue("MQpassword");
		log.debug("host:"+host+"|vhost:"+vhost+"|username:"+username+"|password:"+password);
		//定义连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		//设置服务地址
		factory.setHost(host);
		//端口
		factory.setPort(port);
		//设置账号信息，用户名、密码、vhost
		factory.setVirtualHost(vhost);
		factory.setUsername(username);
		factory.setPassword(password);
		// 通过工程获取连接
		Connection connection = factory.newConnection();
		return connection;
	}

}
